package com.boot.common.exception;

import com.boot.common.po.Result;
import com.boot.common.po.StatusCodeEnum;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;

/**
 *  全局异常处理
 * @author zhangkai
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * @description:
     * 添加全局异常处理流程，根据需要设置需要处理的异常，本文以MethodArgumentNotValidException为例
     * 使用方法：controller层方法加【@RequestBody @Valid】注解
     * @author: zhangkai
     * @date: 2021/4/15 下午2:47
     * @param e:
     * @return java.lang.Object
     * @throws
     **/
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Object MethodArgumentNotValidHandler(MethodArgumentNotValidException e) {
        ArrayList<Object> errors = Lists.newArrayList();
        for (FieldError error : e.getBindingResult().getFieldErrors()) {
            logger.error(error.getField() + ":" + error.getDefaultMessage());
            errors.add(error.getDefaultMessage());
        }
        return Result.error(StatusCodeEnum.ERROR.getCode(), errors.toString());
    }

    @ExceptionHandler(value = BaseException.class)
    public Object BaseExceptionHandler(BaseException e) {
        return Result.error(StatusCodeEnum.ERROR.getCode(), e.getMessage());
    }

    @ExceptionHandler(value = UnAuthorizedException.class)
    public Object UnAuthorizedExceptionHandler(UnAuthorizedException e) {
        return Result.error(e.getCode(), e.getMessage());
    }
}
